package com.landiao.ctrler.weixin;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.landiao.common.Constant;
import com.landiao.common.Constant.PayResult;
import com.landiao.common.Constant.WxTradeType;
import com.landiao.common.factory.ResultMsgFactory;
import com.landiao.common.pojo.EmpOrderInfo;
import com.landiao.common.pojo.Page;
import com.landiao.common.pojo.PayOrderDetail;
import com.landiao.common.pojo.PerformanceDetail;
import com.landiao.common.pojo.PerformanceHisInfo;
import com.landiao.common.pojo.Querier;
import com.landiao.common.pojo.RecordDetail;
import com.landiao.common.pojo.ResultMsg;
import com.landiao.common.utils.CodecUtils;
import com.landiao.common.utils.CommUtil;
import com.landiao.common.utils.DateUtil;
import com.landiao.common.weixin.WxConsts;
import com.landiao.common.weixin.WxErrorException;
import com.landiao.common.weixin.WxMpService;
import com.landiao.common.weixin.bean.WxJsapiSignature;
import com.landiao.common.weixin.bean.WxMenu;
import com.landiao.common.weixin.bean.WxMenu.WxMenuButton;
import com.landiao.common.weixin.bean.WxMpPrepayIdResult;
import com.landiao.common.weixin.bean.WxMpTemplateData;
import com.landiao.common.weixin.bean.WxMpTemplateMessage;
import com.landiao.common.weixin.bean.WxMpUser;
import com.landiao.common.weixin.bean.WxMpXmlMessage;
import com.landiao.common.weixin.bean.WxMpXmlOutTextMessage;
import com.landiao.ctrler.BaseCtrler;
import com.landiao.entities.Appointment;
import com.landiao.entities.Coupon;
import com.landiao.entities.CouponReceive;
import com.landiao.entities.Employee;
import com.landiao.entities.HairdoImg;
import com.landiao.entities.HairdoRecord;
import com.landiao.entities.Mdse;
import com.landiao.entities.NoteDict;
import com.landiao.entities.OrderDetail;
import com.landiao.entities.OrderInfo;
import com.landiao.entities.OrderSchedule;
import com.landiao.entities.PayFlow;
import com.landiao.entities.Role;
import com.landiao.entities.SendTemplate;
import com.landiao.entities.ServiceItemPrice;
import com.landiao.entities.ServiceItemRoleRela;
import com.landiao.entities.SuggestVipMdse;
import com.landiao.entities.Vip;
import com.landiao.service.AppointmentService;
import com.landiao.service.CouponReceiveService;
import com.landiao.service.EmployeeService;
import com.landiao.service.HairdoImgService;
import com.landiao.service.HairdoRecordService;
import com.landiao.service.HolidayService;
import com.landiao.service.ItemCategoryService;
import com.landiao.service.MdseService;
import com.landiao.service.NoteDictService;
import com.landiao.service.OrderInfoService;
import com.landiao.service.OrderScheduleService;
import com.landiao.service.PackageService;
import com.landiao.service.PayFlowService;
import com.landiao.service.RoleCommisionRuleService;
import com.landiao.service.RoleService;
import com.landiao.service.SendTemplateService;
import com.landiao.service.ServiceItemService;
import com.landiao.service.ShopService;
import com.landiao.service.SysConfigService;
import com.landiao.service.VipService;

/**
 * 功能说明:员工微信端
 */
@Controller
@RequestMapping("/weixin/employee")
public class WxEmployeeCtrler extends BaseCtrler{

	private static final String VIP_ORDER_URL="weixin/vip/myOrder";

	@Autowired
	@Qualifier("employeeWxService")
	private WxMpService employeeWxService;

	@Autowired
	@Qualifier("vipWxService")
	private WxMpService vipWxService;

	@Autowired
	private EmployeeService employeeService;

	@Autowired
	private OrderInfoService orderInfoService;

	@Autowired
	private AppointmentService appointService;

	@Autowired
	private OrderScheduleService scheService;

	@Autowired
	private ShopService shopService;

	@Autowired
	private PackageService packageService;

	@Autowired
	private ServiceItemService itemService;

	@Autowired
	private HolidayService holidayService;

	@Autowired
	private VipService vipService;

	@Autowired
	private RoleCommisionRuleService ruleService;

	@Autowired
	private NoteDictService noteDictService;

	@Autowired
	private HairdoImgService hairdoImgService;

	@Autowired
	private HairdoRecordService hairdoRecordService;

	@Autowired
	private SendTemplateService sendTempService;

	@Autowired
	private SysConfigService sysConfigService;

	@Autowired
	private ItemCategoryService itemCategoryService;

	@Autowired
	private MdseService mdseService;

	@Autowired
	private CouponReceiveService couponReceiveService;

	@Autowired
	private PayFlowService payFlowService;
	
	@Autowired
	private RoleService roleService;

	@RequestMapping(method = RequestMethod.GET)
	public void index(HttpServletRequest request,String signature,String timestamp,String nonce,String echostr,HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter();
			if(employeeWxService.checkSignature(timestamp, nonce, signature)){
				log.error("echostr:{}",echostr);
				out.print(echostr);
			}else{
				out.print("error");
			}
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(method = RequestMethod.POST)
	public void index(HttpServletRequest request,HttpServletResponse response){
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
			WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(request.getInputStream());
			log.debug("wxInXml:{}",inMessage.toString());
			String resp = "success";
			if (inMessage.getMsgType().equals(WxConsts.XML_MSG_EVENT)) {//事件
				if(inMessage.getEvent().equals(WxConsts.EVT_SUBSCRIBE)){//关注
					//WxMpUser wxUser = vipWxService.userInfo(inMessage.getFromUserName(), null);
					WxMpXmlOutTextMessage text = new WxMpXmlOutTextMessage();
					text.setContent(employeeWxService.getWxMpConfigStorage().getWelcome());
					text.setCreateTime(System.currentTimeMillis()/1000l);
					text.setFromUserName(inMessage.getToUserName());
					text.setToUserName(inMessage.getFromUserName());
					resp=text.toXml();
				}
				if(inMessage.getEvent().equals(WxConsts.EVT_UNSUBSCRIBE)){//取消关注
					
				}
			}
			PrintWriter out = response.getWriter();
			out.print(resp);
			out.flush();
			out.close();
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
	}

	@RequestMapping("menu")
	@ResponseBody
	public String menu(HttpServletRequest request){
		try {
			WxMenu wxMenu = new WxMenu();
			WxMenuButton button1 = new WxMenuButton();
			button1.setType(WxConsts.BUTTON_VIEW);
			button1.setUrl(this.webSite+"weixin/employee/billing");
			button1.setName("美发开单");

			WxMenuButton button2 = new WxMenuButton();
			button2.setName("个人中心");

			WxMenuButton button21 = new WxMenuButton();
			button21.setType(WxConsts.BUTTON_VIEW);
			button21.setUrl(this.webSite+"weixin/employee/vacate");
			button21.setName("申请休假");

			WxMenuButton button22 = new WxMenuButton();
			button22.setType(WxConsts.BUTTON_VIEW);
			button22.setUrl(this.webSite+"weixin/employee/orderList");
			button22.setName("订单信息");

			WxMenuButton button23 = new WxMenuButton();
			button23.setType(WxConsts.BUTTON_VIEW);
			button23.setUrl(this.webSite+"weixin/employee/myAppoint");
			button23.setName("预约信息");

			button2.getSub_button().add(button21);
			button2.getSub_button().add(button22);
			button2.getSub_button().add(button23);

			WxMenuButton button3 = new WxMenuButton();
			button3.setType(WxConsts.BUTTON_VIEW);
			button3.setUrl(this.webSite+"weixin/employee/myPerformance");
			button3.setName("我的业绩");

			wxMenu.getButton().add(button1);
			wxMenu.getButton().add(button2);
			wxMenu.getButton().add(button3);

			log.debug(wxMenu.toJson());
			// 设置菜单
			employeeWxService.menuCreate(wxMenu);

			//添加模板
			if(Constant.EMPLOYEE_TEMP_MAP.size()==0){
				employeeWxService.templateSetIndustry(Constant.industry_id1, Constant.industry_id2);
				String msgid = employeeWxService.templateAdd(Constant.TEMP_ID_ORDER_EMPLOYEE);

				SendTemplate temp = new SendTemplate();
				temp.setCompId(Constant.comp.getCompId());
				temp.setSendTemplateId(CodecUtils.getUUID());
				temp.setOriginNo(Constant.TEMP_ID_ORDER_EMPLOYEE);
				temp.setPublicNo("EMPLOYEE");
				temp.setTemplateId(msgid);
				//				temp.setTemplateType(templateType);
				temp.setTitle("会员预约通知");

				this.sendTempService.save(temp);

				Constant.EMPLOYEE_TEMP_MAP.put(Constant.TEMP_ID_ORDER_EMPLOYEE, temp);
			}
		} catch (WxErrorException e) {
			log.error(e.getMessage());
			return e.getMessage();
		}
		return "success";
	}

	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login(Model model,String backUrl) {
		if(StringUtils.isNotBlank(backUrl))
			model.addAttribute("backUrl", backUrl);
		return viewName("employee_check");
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg login(String username,String password,HttpSession session) {
		try{
			Employee emp = this.employeeService.getByAccount(username);
			if(emp!=null&&emp.getPasswd().equals(CodecUtils.password(password))){
				WxMpUser wxUser = (WxMpUser)session.getAttribute("wxEmpUser");
				if(StringUtils.isNotBlank(emp.getOperId())){
					if(!wxUser.getOpenid().equals(emp.getOperId())){
						return ResultMsgFactory.fail("账号已绑定其他微信号，请确认！");
					}
				}
				emp.setOperId(wxUser.getOpenid());
				emp.setStatedate(new Date());
				this.employeeService.updateByOperId(emp);
				session.setAttribute("wxEmp", emp);
			}else{
				return ResultMsgFactory.fail("账号或密码错误，请重新输入！");
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error("认证失败：{}",e.getMessage());
			return ResultMsgFactory.fail("认证失败");
		}
		return ResultMsgFactory.success("认证成功");
	}

	/**
	 * 休假页面
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "vacate", method = RequestMethod.GET)
	public String vacate(Model model,HttpSession session){
		//		Employee emp = (Employee)session.getAttribute("wxEmp");
		return viewName("vacate");
	}

	/**
	 * 提交休假信息
	 * @param beginDate
	 * @param endDate
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "vacate", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg vacateSave(Date begintime,Date endtime,String reason,HttpSession session){
		try{
			Employee emp = (Employee)session.getAttribute("wxEmp");
			if(endtime== null){
				endtime = begintime;
			}
			if(begintime== null){
				begintime = endtime;
			}
			if(begintime.after(endtime)){
				return ResultMsgFactory.fail("起始日期不能大于结束日期");
			}
			this.holidayService.batchSave(emp, begintime, endtime, reason);
		}catch(Exception e){
			e.printStackTrace();
			log.error("提交失败：{}",e.getMessage());
			return ResultMsgFactory.fail("提交失败");
		}
		return ResultMsgFactory.success("提交成功");
	}

	/**
	 * 预约处理
	 * @param appoint
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "appointSave", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg appointSave(String reason,String appointId,String state,HttpSession session) {
		// TODO Auto-generated method stub
		Employee emp = (Employee)session.getAttribute("wxEmp");
		Appointment appoint = this.appointService.getById(appointId);
		try{
			if(emp.getEmployeeId().equals(appoint.getEmployeeId())){
				if(appoint.getState()!=null){
					return ResultMsgFactory.fail("该预约已处理过");
				}
				if(appoint.getAppointmentTime().compareTo(new Date())<=0){
					return ResultMsgFactory.fail("该预约已过期");
				}
				appoint.setState(state);
				appoint.setRefuseReason(reason);
				this.appointService.update(appoint);
			}else{
				return ResultMsgFactory.fail("提交失败");
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error("提交失败：{}",e.getMessage());
			return ResultMsgFactory.fail("提交失败");
		}
		try{
			SendTemplate temp = null;
			if(appoint.getState().equals("10A")){//确认预约
				temp = Constant.VIP_TEMP_MAP.get(Constant.TEMP_ID_ORDER_SUCCESS);
			}else{
				temp = Constant.VIP_TEMP_MAP.get(Constant.TEMP_ID_ORDER_FAIL);
			}
			if(temp!=null){
				Vip vip = this.vipService.getById(appoint.getVipId());
				WxMpTemplateMessage message = new WxMpTemplateMessage();
				message.setUrl(this.webSite+VIP_ORDER_URL);
				message.setTouser(vip.getOperId());
				message.setTopcolor("#FF0000");
				message.setTemplate_id(temp.getTemplateId());
				if(appoint.getState().equals("10A")){//确认预约
					/**
					 * {first.DATA}}
						会员名称：{{keyword1.DATA}}
						预约时间：{{keyword2.DATA}}
						预约门店：{{keyword3.DATA}}
						预约项目：{{keyword4.DATA}}
						预约美发师：{{keyword5.DATA}}
						{{remark.DATA}}
					 */

					message.getData().put("first", new WxMpTemplateData("您好，您已预约成功！"));
					message.getData().put("keyword1", new WxMpTemplateData(vip.getName()));
					message.getData().put("keyword2", new WxMpTemplateData(DateUtil.date2Str(appoint.getAppointmentTime(), DateUtil.MMDDHHmm)));
					message.getData().put("keyword3", new WxMpTemplateData(emp.getShopName()));
					message.getData().put("keyword4", new WxMpTemplateData(appoint.getServiceItemNames()));
					message.getData().put("keyword5", new WxMpTemplateData(emp.getName()));
					message.getData().put("remark", new WxMpTemplateData("\n为了完美的服务体验，请提前安排好时间。"));
				}else{//拒绝预约
					/**
					 * {{first.DATA}}
						预约门店：{{keyword1.DATA}}
						预约时间：{{keyword2.DATA}}
						预约服务：{{keyword3.DATA}}
						失败原因：{{keyword4.DATA}}
						{{remark.DATA}}
					 */
					message.getData().put("first", new WxMpTemplateData("尊敬的"+vip.getName()+"：非常抱歉，您预约失败！"));
					message.getData().put("keyword1", new WxMpTemplateData(emp.getShopName()));
					message.getData().put("keyword2", new WxMpTemplateData(DateUtil.date2Str(appoint.getAppointmentTime(), DateUtil.MMDDHHmm)));
					message.getData().put("keyword3", new WxMpTemplateData(appoint.getServiceItemNames()));
					message.getData().put("keyword4", new WxMpTemplateData(appoint.getRefuseReason()==null?"":appoint.getRefuseReason()));
					message.getData().put("remark", new WxMpTemplateData("\n您可以尝试其它时段继续预约，我们将恭候你的光临谢谢。\n点击重新预约。"));
				}
				vipWxService.templateSend(message);
			}
		}catch(Exception e){
			e.printStackTrace();
			log.error("微信模板消息发送失败：{}",e.getMessage());
		}
		return ResultMsgFactory.success("提交成功");
	}

	@RequestMapping(value = "myAppoint")
	public String myAppoint(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		return viewName("order_info");
	}

	@RequestMapping(value = "myAppointPage")
	@ResponseBody
	public Page<Appointment> myAppointPage(Model model,HttpSession session,Querier querier) {
		// TODO Auto-generated method stub
		Employee emp = (Employee)session.getAttribute("wxEmp");
		Appointment appoint = new Appointment();
		appoint.setEmployeeId(emp.getEmployeeId());
		Page<Appointment> page = this.appointService.queryByPage(querier, appoint);
		return page;
	}

	@RequestMapping(value = "serviceRecord/{vipId}")
	public String vipServiceRecord(Model model,HttpSession session,@PathVariable String vipId) {
		// TODO Auto-generated method stub
		model.addAttribute("vipId", vipId);
		return viewName("service_record");
	}

	@RequestMapping(value = "serviceRecordPage")
	@ResponseBody
	public Page<RecordDetail> vipServiceRecordPage(Model model,HttpSession session,Querier querier,String vipId) {
		// TODO Auto-generated method stub
		//		Employee emp = (Employee)session.getAttribute("wxEmp");
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setVipId(vipId);

		Page<OrderInfo> page = this.orderInfoService.queryByPageFromWx(querier, orderInfo);

		//转为页面显示的page
		Page<RecordDetail> pageMap = new Page<>();
		pageMap.setPage(page.getPage());
		pageMap.setPageSize(page.getPageSize());
		pageMap.setRecords(page.getRecords());
		pageMap.setTotal(page.getTotal());
		if(page.getRows()!=null&&page.getRows().size()>0){
			Map<String, RecordDetail> map = new LinkedHashMap<>();
			for(OrderInfo info : page.getRows()){
				String month = DateUtil.date2Str(info.getCreTime(), "yyM");
				info.setCreDateStr(CommUtil.formatDateLocale(info.getCreTime()));
				RecordDetail tmp= map.get(month);
				if(tmp==null){
					tmp = new RecordDetail();
					tmp.setMonth(month);
					tmp.setList(new ArrayList<OrderInfo>());
					map.put(month, tmp);
				}
				tmp.getList().add(info);
			}
			pageMap.setRows(new ArrayList<RecordDetail>(map.values()));
		}
		return pageMap;
	}

	@RequestMapping(value = "billing")
	public String billing(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		return viewName("billing");
	}

	@RequestMapping(value = "billingFlow")
	public String billingFlow(Model model,HttpSession session,String vipId,String orderInfoId,String orderScheduleId) {
		// TODO Auto-generated method stub
		Employee emp = (Employee)session.getAttribute("wxEmp");
		if(StringUtils.isNotBlank(vipId))
			model.addAttribute("vipId", vipId);
		if(StringUtils.isNotBlank(orderInfoId)){
			OrderInfo orderInfo = this.orderInfoService.getWithDetail(orderInfoId);
			model.addAttribute("orderInfo", orderInfo);
			model.addAttribute("vipId", orderInfo.getVipId());
		}
		if(StringUtils.isNotBlank(orderScheduleId)){
			OrderSchedule sche = this.scheService.getById(orderScheduleId);
			model.addAttribute("orderScheduleId", orderScheduleId);
			model.addAttribute("orderDetailId", sche.getOrderDetailId());
		}
		List<Mdse> mdses = this.mdseService.getListByCompId(emp.getCompId());
		model.addAttribute("mdses", mdses);
		return viewName("billing_flow");
	}

	@RequestMapping(value = "searchVip")
	@ResponseBody
	public ResultMsg searchVip(String phone,HttpSession session) {
		try{
			Vip vip = this.vipService.getByVipNo(phone);
			if(vip==null){
				return ResultMsgFactory.fail("未找到指定会员信息");
			}
			ResultMsg resultMsg = ResultMsgFactory.successMsg();
			resultMsg.addParam("vip", vip);

			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setVipId(vip.getVipId());
			Querier querier = new Querier();
			querier.setRows(1);
			querier.setPage(1);
			Page<OrderInfo> page = this.orderInfoService.queryByPageFromWx(querier, orderInfo);
			if(page.getRows()!=null&&page.getRows().size()>0){
				resultMsg.addParam("order", page.getRows().get(0));
			}
			Appointment appoint = new Appointment();
			appoint.setVipId(vip.getVipId());
			appoint.setAppointmentTime(new Date());
			appoint.setState("10A");
			Page<Appointment> appPage = this.appointService.queryByPage(querier, appoint);
			if(appPage.getRows()!=null&&appPage.getRows().size()>0){
				appoint = appPage.getRows().get(0);
				String titleName=this.employeeService.getById(appoint.getEmployeeId()).getTitleName();
				appoint.setEmployeeName(appoint.getEmployeeName()+"（"+titleName+"）");
				resultMsg.addParam("appoint", appoint);
			}
			return resultMsg;
		}catch(Exception e){
			e.printStackTrace();
			log.error("查询会员失败：{}",e.getMessage());
			return ResultMsgFactory.fail("查询会员失败");
		}
	}

	@RequestMapping(value = "vipDetail/{vipId}")
	public String vipDetail(Model model,HttpSession session,@PathVariable String vipId) {
		// TODO Auto-generated method stub
		Vip vip = this.vipService.getByIdWithDict(vipId);
		model.addAttribute("vip", vip);
		List<SuggestVipMdse> list = this.vipService.getSuggestVipMdseListByVipId(vipId);

		NoteDict noteDict = new NoteDict();
		noteDict.setColName("CATEGORY");
		noteDict.setTabName("MDSE");
		List<NoteDict> dictlist = noteDictService.getNoteDictList(noteDict);

		SuggestVipMdse scalp = new SuggestVipMdse();//头皮
		SuggestVipMdse hair = new SuggestVipMdse();//发质
		for(NoteDict dict:dictlist){
			if(dict.getVal1().equals("TPHLCP"))
				scalp.setMdseCategoryName(dict.getVal1Desc());
			else if(dict.getVal1().equals("ZDFZJJCP"))
				hair.setMdseCategoryName(dict.getVal1Desc());
		}
		if(list!=null){
			for(SuggestVipMdse su:list){
				if(su.getMdseCategory().equals("TPHLCP"))
					scalp.setMdseName(su.getMdseName());
				else if(su.getMdseCategory().equals("ZDFZJJCP"))
					hair.setMdseName(su.getMdseName());
			}
		}
		model.addAttribute("scalp", scalp);
		model.addAttribute("hair", hair);
		return viewName("vip_detail");
	}

	@RequestMapping(value = "hairdoRecord/{orderInfoId}", method = RequestMethod.GET)
	@ResponseBody
	public HairdoRecord hairdoRecord(@PathVariable String orderInfoId) {
		// TODO Auto-generated method stub
		HairdoRecord record = this.hairdoRecordService.getByOrderInfoId(orderInfoId);
		if(record!=null){
			record.setImgList(this.hairdoImgService.getImgsByHairdoRecordId(record.getHairdoRecordId()));
		}else{
			record = new HairdoRecord();
		}
		return record;
	}

	/**
	 * 按角色返回员工列表
	 * @param shopId
	 * @return
	 */
	@RequestMapping(value = "shop/{shopId}/employee", method = RequestMethod.GET)
	@ResponseBody
	public Map<String,List<Employee>> shopEmployee(@PathVariable String shopId) {
		// TODO Auto-generated method stub
		List<Employee> list = this.employeeService.getEmployeeListByShopIdAndHasOperId(shopId);
		Map<String,List<Employee>> map = new HashMap<>();
		for(Employee emp : list){
			List<Employee> tmpList= map.get(emp.getRoleId());
			if(tmpList==null){
				tmpList = new ArrayList<>();
				map.put(emp.getRoleId(), tmpList);
			}
			tmpList.add(emp);
		}
		return map;
	}

	@RequestMapping(value = "shop/{shopId}/role/{roleId}", method = RequestMethod.GET)
	@ResponseBody
	public List<Employee> getEmpByShopAndRole(@PathVariable String shopId,@PathVariable String roleId) {
		// TODO Auto-generated method stub
		return this.employeeService.getEmployeeListByShopIdAndRole(shopId, roleId);
	}

	@RequestMapping(value = "shop/{shopId}/service/{serviceId}", method = RequestMethod.GET)
	@ResponseBody
	public ResultMsg getEmpByShopAndService(@PathVariable String shopId,@PathVariable String serviceId) {
		// TODO Auto-generated method stub
		ResultMsg resultMsg = ResultMsgFactory.successMsg();
		List<ServiceItemRoleRela> roles = this.itemService.getRoleRelaByServiceItemId(serviceId);
		for(ServiceItemRoleRela role:roles){
			List<Employee> emps = this.employeeService.getEmployeeListByShopIdAndRole(shopId, role.getRoleId());
			resultMsg.addParam(role.getRoleId(),emps);
		}

		return resultMsg;
	}

	@RequestMapping(value = "shop/{shopId}/service/{serviceId}/role", method = RequestMethod.GET)
	@ResponseBody
	public List<ServiceItemRoleRela> getRoleByShopAndService(@PathVariable String shopId,@PathVariable String serviceId) {
		// TODO Auto-generated method stub
		List<ServiceItemRoleRela> roles = this.itemService.getRoleRelaByServiceItemId(serviceId);
		return roles;
	}

	@RequestMapping(value = "shop/{shopId}/package/{packageId}/role", method = RequestMethod.GET)
	@ResponseBody
	public List<ServiceItemPrice> getRoleByShopAndPackage(@PathVariable String shopId,@PathVariable String packageId) {
		// TODO Auto-generated method stub
		List<ServiceItemPrice> prices = this.itemService.getPriceListByShopAndPackage(shopId, packageId);
		for(ServiceItemPrice price:prices){
			List<ServiceItemRoleRela> roles = this.itemService.getRoleRelaByServiceItemId(price.getServiceItemId());
			price.setRoleRelaList(roles);
		}
		return prices;
	}

	@RequestMapping(value = "orderSave", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg orderSave(OrderInfo orderInfo,String orderScheduleId,String type,HttpSession session){
		try {
			Employee emp = (Employee)session.getAttribute("wxEmp");
			if(StringUtils.isNotEmpty(orderInfo.getOrderInfoId())){
				OrderInfo order = this.orderInfoService.getById(orderInfo.getOrderInfoId());
				if(order==null){
					return ResultMsgFactory.fail("订单不存在");
				}
				orderInfo.setCompId(emp.getCompId());
				orderInfo.setPayState(order.getPayState());
				if("next".equals(type)){//下一步
					this.orderInfoService.updateOrder(orderInfo, orderScheduleId,emp.getEmployeeId());
					if(!orderInfo.getPayState().equals("10A")){
						List<OrderDetail> details = this.orderInfoService.getNotOverDetail(orderInfo.getOrderInfoId());
						if(details==null||details.size()==0){
							ResultMsg msg = ResultMsgFactory.success("服务已全部完成，正在跳往结帐页面");
							msg.addParam("pay", true);
							return msg;
						}
					}
				}
				else
					this.orderInfoService.updateOrder(orderInfo, null,emp.getEmployeeId());
			}else{
				orderInfo.setEmployeeId(emp.getEmployeeId());
				orderInfo.setCompId(emp.getCompId());
				this.orderInfoService.saveOrder(orderInfo);
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error("保存订单失败：{}",e.getMessage());
			return ResultMsgFactory.fail("保存失败");
		}
		return ResultMsgFactory.successMsg();
	}

	@RequestMapping(value = "orderList")
	public String orderList(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		return viewName("order_list");
	}

	@RequestMapping(value = "orderListPage")
	@ResponseBody
	public Page<EmpOrderInfo> orderListPage(Model model,HttpSession session,Querier querier) {
		// TODO Auto-generated method stub
		Employee emp = (Employee)session.getAttribute("wxEmp");
		Page<EmpOrderInfo> page = this.orderInfoService.queryEmpOrderByPage(querier, emp.getEmployeeId());
		return page;
	}

	@RequestMapping(value = "deleteOrderDetail")
	@ResponseBody
	public ResultMsg deleteOrderDetail(String orderInfoId,String detailIds) {
		try{
			OrderInfo order = this.orderInfoService.getById(orderInfoId);
			if(!order.getPayState().equals("10X")){
				return ResultMsgFactory.fail("订单已结算，不能删除，请联系管理员");
			}
			List<String> details = Arrays.asList(detailIds.split(","));
			List<OrderDetail> list = this.orderInfoService.getHasService(details);
			if(list!=null&&list.size()>0){
				return ResultMsgFactory.fail("项目已服务或服务中，不能删除");
			}
			this.orderInfoService.batchDeleteDetails(details);
			ResultMsg resultMsg = ResultMsgFactory.successMsg();
			return resultMsg;
		}catch(Exception e){
			e.printStackTrace();
			log.error("删除项目失败：{}",e.getMessage());
			return ResultMsgFactory.failMsg();
		}
	}

	@RequestMapping(value = "orderPay/{orderInfoId}")
	public String orderPay(@PathVariable String orderInfoId,Model model){
		OrderInfo orderInfo = this.orderInfoService.getWithDetail(orderInfoId);
		BigDecimal amount = new BigDecimal("0");
		List<PayOrderDetail> details = new ArrayList<>();
		List<String> serviceItems = new ArrayList<>();
		for(OrderDetail detail:orderInfo.getDetailList()){
			PayOrderDetail payDetail = new PayOrderDetail();
			if(detail.getPackageId()==null&&detail.getServiceItemId()!=null){
				serviceItems.add(detail.getServiceItemId());
				payDetail.setServiceItemId(detail.getServiceItemId());
			}
			payDetail.setServiceItemName(detail.getMdseServiceName());
			if(detail.getMdseId()!=null){
				BigDecimal mdsePrice = detail.getPrice().multiply(new BigDecimal(detail.getMdseNum().toString()));
				payDetail.setMdseNum(detail.getMdseNum());
				payDetail.setPrice(mdsePrice);
				amount = amount.add(mdsePrice);
			}else{
				StringBuilder empNames = new StringBuilder();
				for(OrderSchedule sche:detail.getScheList()){
					if(StringUtils.isNotEmpty(sche.getEmployeeName()))
						empNames.append(sche.getEmployeeName()).append("、");
				}
				if(empNames.length()>1)
					payDetail.setEmployeeNames(empNames.substring(0, empNames.length()-1));
				payDetail.setPrice(detail.getPrice());
				amount = amount.add(detail.getPrice());
			}
			details.add(payDetail);
		}
		String total = null;
		
		orderInfo.setAmount(amount.setScale(1, BigDecimal.ROUND_HALF_UP));
		total = orderInfo.getAmount().toString();
		if(orderInfo.getShouldPay()!=null&&orderInfo.getPayState().equals("10I")&&orderInfo.getAmount().compareTo(orderInfo.getShouldPay())!=0){//已结算
			String sub = orderInfo.getAmount().subtract(orderInfo.getShouldPay()).setScale(1, BigDecimal.ROUND_HALF_UP).toString();
			total = orderInfo.getAmount()+"-"+sub+"="+orderInfo.getShouldPay();
		}else{
			orderInfo.setShouldPay(orderInfo.getAmount());
		}
		model.addAttribute("total", total);
		this.orderInfoService.update(orderInfo);
		if(orderInfo.getVipId()!=null&&orderInfo.getPayState().equals("10X")){
			Vip vip = this.vipService.getById(orderInfo.getVipId());
			if(serviceItems.size()>0){
				List<Coupon> coupons = this.couponReceiveService.getValidCoupon(vip.getVipId(), vip.getShopId(), serviceItems);
				if(coupons!=null&&coupons.size()>0){
					model.addAttribute("coupons", coupons);
				}
			}
			model.addAttribute("vip", vip);
		}
		model.addAttribute("details", details);
		model.addAttribute("orderInfo", orderInfo);
		return viewName("check_out");
	}

	@RequestMapping(value = "orderPaySave")
	@ResponseBody
	public ResultMsg orderPaySave(String orderInfoId,String payWay,String serviceItemId) {
		try{
			OrderInfo orderInfo = this.orderInfoService.getWithDetail(orderInfoId);
			if(orderInfo==null){
				return ResultMsgFactory.fail("订单不存在");
			}
			if(orderInfo.getPayState().equals("10A")){
				return ResultMsgFactory.fail("订单已支付");
			}
			ResultMsg resultMsg = this.orderInfoService.saveOrderPay(orderInfo, payWay, serviceItemId);
			return resultMsg;
		}catch(Exception e){
			e.printStackTrace();
			log.error("订单支付失败：{}",e.getMessage());
			return ResultMsgFactory.fail("支付失败，请重试！");
		}
	}

	@RequestMapping(value = "orderPayQrcode")
	public String orderPayQrcode(String orderInfoId,String serviceItemId,Model model, RedirectAttributes redirectAttr,HttpServletRequest request){
		OrderInfo orderInfo = this.orderInfoService.getWithDetail(orderInfoId);
		if(orderInfo.getPayState().equals("10A")){
			redirectAttr.addFlashAttribute("resultMsg",
					ResultMsgFactory.fail("订单已支付"));
			return redirectToUrl(viewName("orderPay/"+orderInfoId));
		}
		if(orderInfo.getVipId()!=null)
			model.addAttribute("vipId", orderInfo.getVipId());
		PayFlow payFlow = null;
		if(orderInfo.getPayState().equals("10X")){
			try{
				if(StringUtils.isNotEmpty(serviceItemId)){
					model.addAttribute("serviceItemId", serviceItemId);
					CouponReceive cr = this.couponReceiveService.getValidByVipIdAndServiceItemId(orderInfo.getVipId(), serviceItemId);
					if(cr==null){
						redirectAttr.addFlashAttribute("resultMsg",
								ResultMsgFactory.fail("代金券已过期或已使用,请重新选择"));
						return redirectToUrl(viewName("orderPay/"+orderInfoId));
					}
					cr.setIsUsed("10X");
					cr.setStatedate(new Date());
					this.couponReceiveService.update(cr);

					for(OrderDetail detail:orderInfo.getDetailList()){
						if(serviceItemId.equals(detail.getServiceItemId())&&detail.getPackageId()==null){
							for(OrderSchedule sche:detail.getScheList()){
								sche.setIsDk("10A");
								this.scheService.update(sche);
							}
							orderInfo.setShouldPay(orderInfo.getAmount().subtract(detail.getPrice()));
							break;
						}
					}
				}

				payFlow = new PayFlow();
				payFlow.setPayFlowId(CodecUtils.getUUID());
				payFlow.setCompId(orderInfo.getCompId());
				payFlow.setVipId(orderInfo.getVipId());
				payFlow.setFlowNo(orderInfo.getOrderNo());
				payFlow.setAmount(orderInfo.getShouldPay());
				payFlow.setPaySource(Constant.PAY_SOURCE_XF);
				payFlow.setPayWay(Constant.PAY_WAY_ZX);
				payFlow.setTradeType(WxTradeType.NATIVE.toString());
				payFlow.setStatedate(new Date());
				payFlow.setPrepayId(serviceItemId);
				orderInfo.setPayState("10I");
				this.payFlowService.save(payFlow, orderInfo);
			}catch(Exception e){
				e.printStackTrace();
				log.error("支付下单失败：{}",e.getMessage());
				redirectAttr.addFlashAttribute("resultMsg",
						ResultMsgFactory.fail("支付失败，请稍后重试"));
				return redirectToUrl(viewName("orderPay/"+orderInfoId));
			}
		}

		try{
			String ip = request.getLocalAddr();
			log.debug("ip：{}",ip);
			WxMpPrepayIdResult result = this.employeeWxService.getPrepayId(null, orderInfo.getOrderNo(), orderInfo.getShouldPay(), Constant.PAY_BODY_XF, WxTradeType.NATIVE.toString(), ip, this.webSite+Constant.WX_PAY_NOTIFY_URL,orderInfo.getOrderNo(),null);
			String codeUrl = result.getCode_url();
			if (StringUtils.isEmpty(codeUrl)) {
				throw new RuntimeException("get codeUrl error");
			}
			model.addAttribute("amount", orderInfo.getShouldPay());
			model.addAttribute("orderInfoId", orderInfoId);
			model.addAttribute("orderNo", orderInfo.getOrderNo());
			model.addAttribute("codeUrl", codeUrl);

			return viewName("qrcode");
		}catch(Exception e){
			if(payFlow!=null){
				payFlow.setPayResult(PayResult.PAYERROR.toString());
				payFlow.setTradeStateDesc("微信统一下单失败");
				payFlow.setCompleteTime(new Date());
				this.payFlowService.update(payFlow);
			}
			e.printStackTrace();
			log.error("微信预下单失败：{}",e.getMessage());
			redirectAttr.addFlashAttribute("resultMsg",
					ResultMsgFactory.fail("微信统一下单失败，请稍后重试"));
			return redirectToUrl(viewName("orderPay/"+orderInfoId));
		}
	}

	@RequestMapping(value = "payResult")
	@ResponseBody
	public ResultMsg payResult(String orderNo,boolean payOver) {
		if(payOver){
			return this.payFlowService.checkXfWxPayInfo(orderNo, null);
		}else{
			PayFlow payFlow = this.payFlowService.getByFlowNoAndPayWay(orderNo, Constant.PAY_WAY_ZX);
			if(payFlow==null){
				return ResultMsgFactory.fail("未找到支付记录，有疑问请联系客服");
			}
			if(PayResult.PAYERROR.toString().equals(payFlow.getPayResult())){
				ResultMsg msg= ResultMsgFactory.fail("支付失败，请稍后重试");
				msg.addParam("error", true);
				return msg;
			}else if(PayResult.SUCCESS.toString().equals(payFlow.getPayResult())){//支付成功
				return ResultMsgFactory.successMsg();
			}else{
				return ResultMsgFactory.failMsg();
			}
		}
	}

	@RequestMapping(value = "orderPayByYE")
	@ResponseBody
	public ResultMsg orderPayByYE(String orderInfoId,String serviceItemId) {
		try{
			OrderInfo orderInfo = this.orderInfoService.getWithDetail(orderInfoId);
			if(orderInfo==null){
				return ResultMsgFactory.fail("订单不存在");
			}
			if(orderInfo.getPayState().equals("10A")){
				return ResultMsgFactory.fail("订单已支付");
			}
			BigDecimal amount = new BigDecimal("0");
			for(OrderDetail detail:orderInfo.getDetailList()){
				if(detail.getMdseId()!=null){
					BigDecimal mdsePrice = detail.getNoVipPrice().multiply(new BigDecimal(detail.getMdseNum().toString()));
					amount = amount.add(mdsePrice);
				}else{
					amount = amount.add(detail.getNoVipPrice());
				}
			}
			if(StringUtils.isNotEmpty(serviceItemId)&&orderInfo.getPayState().equals("10X")){
				CouponReceive cr = this.couponReceiveService.getValidByVipIdAndServiceItemId(orderInfo.getVipId(), serviceItemId);
				if(cr!=null){
					for(OrderDetail detail:orderInfo.getDetailList()){
						if(serviceItemId.equals(detail.getServiceItemId())&&detail.getPackageId()==null){
							for(OrderSchedule sche:detail.getScheList()){
								sche.setIsDk("10A");
							}
							amount = amount.subtract(detail.getPrice());
							break;
						}
					}
				}
			}
			ResultMsg resultMsg = ResultMsgFactory.successMsg();
			resultMsg.addParam("amount", amount.setScale(1, BigDecimal.ROUND_HALF_UP));
			return resultMsg;
		}catch(Exception e){
			e.printStackTrace();
			log.error("余额支付结算失败：{}",e.getMessage());
			return ResultMsgFactory.fail("余额支付结算失败，请重试！");
		}
	}
	
	@RequestMapping(value = "vipInfo")
	public String vipInfo(Model model,HttpSession session,String vipId,String orderInfoId,HttpServletRequest request) {
		// TODO Auto-generated method stub
		Employee emp = (Employee)session.getAttribute("wxEmp");
		if(StringUtils.isNotEmpty(vipId)){
			Vip vip = this.vipService.getById(vipId);
			model.addAttribute("vip", vip);
			if(vip.getBirthday()!=null)
				model.addAttribute("birthday", DateUtil.date2Str(vip.getBirthday(), DateUtil.DATAFORMAT_STR));
		}
		
		if(orderInfoId!=null)
			model.addAttribute("orderInfoId", orderInfoId);

		NoteDict noteDict = new NoteDict();
		noteDict.setTabName("VIP");
		List<NoteDict> vipDictlist = noteDictService.getNoteDictList(noteDict);
		Map<String, List<NoteDict>> vipDictMap = new HashMap<>();
		for(NoteDict dict:vipDictlist){
			List<NoteDict> tmpList = vipDictMap.get(dict.getColName());
			if(tmpList==null){
				tmpList = new ArrayList<>();
				vipDictMap.put(dict.getColName(), tmpList);
			}
			tmpList.add(dict);
		}
		model.addAttribute("dictMap", vipDictMap);

		noteDict.setColName("CATEGORY");
		noteDict.setTabName("MDSE");
		List<NoteDict> mdseDictlist = noteDictService.getNoteDictList(noteDict);

		SuggestVipMdse scalp = new SuggestVipMdse();//头皮
		SuggestVipMdse hair = new SuggestVipMdse();//发质
		for(NoteDict dict:mdseDictlist){
			if(dict.getVal1().equals("TPHLCP")){
				scalp.setMdseCategory("TPHLCP");
				scalp.setMdseCategoryName(dict.getVal1Desc());
			}	
			else if(dict.getVal1().equals("ZDFZJJCP")){
				hair.setMdseCategory("ZDFZJJCP");
				hair.setMdseCategoryName(dict.getVal1Desc());
			}
		}
		model.addAttribute("scalp", scalp);
		model.addAttribute("hair", hair);

		Map<String, List<ServiceItemPrice>> map = new LinkedHashMap<>();
		List<ServiceItemPrice> priceList = this.itemService.getPriceListByShop(emp.getShopId());
		if(priceList!=null&& priceList.size()>0){
			for(ServiceItemPrice price:priceList){
				List<ServiceItemPrice> tmpList= map.get(price.getItemCategoryName());
				if(tmpList==null){
					tmpList = new ArrayList<>();
					map.put(price.getItemCategoryName(), tmpList);
				}
				tmpList.add(price);
			}
		}
		model.addAttribute("serviceMap", map);
		List<Mdse> mdses = this.mdseService.getListByCompId(emp.getCompId());
		model.addAttribute("mdses", mdses);
		
		model.addAttribute("appid", employeeWxService.getWxMpConfigStorage().getAppId());
		try {
			StringBuffer url = request.getRequestURL();
			if (request.getQueryString() != null) {
				url.append("?");
				url.append(request.getQueryString());
			}
			WxJsapiSignature sign = employeeWxService.createJsapiSignature(url.toString());
			model.addAttribute("sign", sign);
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return viewName("vip_info");
	}

	@InitBinder("hairdoRecord")  
	public void initBinderFormBean1(WebDataBinder binder) {    
		binder.setFieldDefaultPrefix("hairdoRecord.");
	}  
	@InitBinder("vip")  
	public void initBinderFormBean2(WebDataBinder binder) {    
		binder.setFieldDefaultPrefix("vip.");
	}  

	@RequestMapping(value = "saveVipInfo")
	@ResponseBody
	public ResultMsg saveVipInfo(Vip vip,HairdoRecord hairdoRecord,String hairMdse,String scalpMdse,HttpSession session) {
		Employee emp = (Employee)session.getAttribute("wxEmp");
		try{
			if(StringUtils.isEmpty(vip.getVipId())){
				Vip vipByPhone = this.vipService.getByVipNo(vip.getPhoneNo());
				if(vipByPhone!=null){
					return ResultMsgFactory.fail("该手机号已经注册！");
				}
			}
			
			String preUrl=getRequest().getScheme()+ "://"+getRequest().getServerName()+ ":" +
					 getRequest().getServerPort()+ getRequest().getContextPath() + "/file/";
			String prePath=getSession().getServletContext().getRealPath("/")+"file/";
			
			vip.setCompId(emp.getCompId());
			vip.setShopId(emp.getShopId());
			if(StringUtils.isNotEmpty(vip.getPhoto())&&vip.getPhoto().indexOf("http")<0){
				String filename = CodecUtils.getUUID()+".jpg";
				String fileUrl = preUrl+filename;
				final String filePath =prePath+filename;
				final String mediaId = vip.getPhoto();
				DOWN_FILE_EXECUTOR_SERVICE.execute(new Thread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						int i =0;
						while(i<3){
							try {
								boolean result = employeeWxService.mediaDownload(mediaId, filePath);
								if(result){
									break;
								}
							} catch (WxErrorException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							i++;
						}
					}
				}));
				
				vip.setPhoto(fileUrl);
			}
			if(hairdoRecord!=null&&hairdoRecord.getImgList()!=null){
				hairdoRecord.setEmployeeId(emp.getEmployeeId());
				hairdoRecord.setCompId(vip.getCompId());
				hairdoRecord.setHaircutDate(new Date());
				//hairdoRecord.setVipId(vip.getVipId());
				for(HairdoImg img:hairdoRecord.getImgList()){
					if(StringUtils.isNotEmpty(img.getImg())){
						String filename = CodecUtils.getUUID()+".jpg";
						String fileUrl = preUrl+filename;
						final String filePath =prePath+filename;
						final String mediaId = img.getImg();
						DOWN_FILE_EXECUTOR_SERVICE.execute(new Thread(new Runnable() {
							@Override
							public void run() {
								// TODO Auto-generated method stub
								int i =0;
								while(i<3){
									try {
										boolean result = employeeWxService.mediaDownload(mediaId, filePath);
										if(result){
											break;
										}
									} catch (WxErrorException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
									i++;
								}
								
							}
						}));
						img.setImg(fileUrl);
					}
				}
			}
			this.vipService.updateVipInfo(vip, hairdoRecord, hairMdse,scalpMdse);
		}catch(Exception e){
			e.printStackTrace();
			log.error("会员信息保存失败：{}",e.getMessage());
			return ResultMsgFactory.fail("保存失败！");
		}
		return ResultMsgFactory.successMsg();
	}

	/**
	 * 历史业绩
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "myPerformance")
	public String myPerformance(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		Employee emp = (Employee)session.getAttribute("wxEmp");
		Map<String, BigDecimal> perforMap = this.scheService.getPerformanceByEmployeeId(emp.getCompId(), emp.getEmployeeId(), emp.getRoleId());
		model.addAttribute("perforMap", perforMap);
		model.addAttribute("emp", emp);
		String progress = null;
		if(emp.getTarget()==0){
			progress="100%";
		}else{
			BigDecimal amount = perforMap.get("monthAmount");

			progress=amount.divide(new BigDecimal(Integer.toString(emp.getTarget())),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")).intValue()+"%";
		}
		model.addAttribute("progress", progress);

		Date nowDate = new Date();
		Querier dayQuerier = new Querier();
		dayQuerier.set("beginTime", DateUtil.getStartTime(nowDate));
		dayQuerier.set("endTime", DateUtil.getEndTime(nowDate));
		dayQuerier.set("state", "10F");
		dayQuerier.set("shopId", emp.getShopId());
		Querier monthQuerier = new Querier();
		monthQuerier.set("beginTime", DateUtil.getStartTime(DateUtil.getMonthFirstDate(nowDate, 0)));
		monthQuerier.set("endTime", DateUtil.getEndTime(nowDate));
		monthQuerier.set("state", "10F");
		monthQuerier.set("shopId", emp.getShopId());
		
		Role queRole = new Role();
		queRole.setCompId(emp.getCompId());
		List<Role> roles = this.roleService.getListRole(queRole);
		for(Role role:roles){
			dayQuerier.set("roleId", role.getRoleId());
			monthQuerier.set("roleId", role.getRoleId());
			List<OrderSchedule> dayRank = this.scheService.getPerformanceRank(dayQuerier);
			List<OrderSchedule> monthRank = this.scheService.getPerformanceRank(monthQuerier);
			
			Map<String, Object> map = new HashMap<>();
			map.put("day", dayRank);
			map.put("month", monthRank);
			map.put("name", role.getName());
			model.addAttribute(role.getRoleId(), map);
		}

		model.addAttribute("month", DateUtil.date2Str(nowDate, "M月"));
		return viewName("my_performance");
	}

	/**
	 * 历史业绩
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "performanceHis")
	public String performanceHis(Model model,HttpSession session) {
		// TODO Auto-generated method stub
		Employee emp = (Employee)session.getAttribute("wxEmp");
		Date endTime = DateUtil.getEndTime(new Date());
		Date beginTime = DateUtil.getStartTime(DateUtil.getMonthFirstDate(new Date(), -3));
		List<PerformanceHisInfo> list = this.scheService.getPerformanceHisByEmployeeId(emp.getCompId(),emp.getEmployeeId(),beginTime,endTime,emp.getRoleId());
		model.addAttribute("list", list);
		return viewName("performance_his");
	}

	/**
	 * 业绩明细
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "performanceDetail")
	public String performanceDetail(Model model,HttpSession session,String dayType,String type) {
		// TODO Auto-generated method stub
		Employee emp = (Employee)session.getAttribute("wxEmp");
		Map<String,List<PerformanceDetail>> map = this.scheService.getPerformanceDetail(emp.getCompId(),emp.getEmployeeId(), emp.getRoleId(), dayType, type);
		model.addAttribute("serviceList", map.get("service"));
		model.addAttribute("mdseList", map.get("mdse"));
		if("base".equals(type)){
			model.addAttribute("name", "业绩");
		}else{
			model.addAttribute("name", "提成");
		}
		if("month".equals(dayType)){
			model.addAttribute("dayName", "本月");
		}else{
			model.addAttribute("dayName", "今日");
		}
		return viewName("performance_detail");
	}

	@RequestMapping(value = "changeTarget")
	@ResponseBody
	public ResultMsg changeTarget(Integer target,HttpSession session) {
		Employee emp = (Employee)session.getAttribute("wxEmp");
		emp.setTarget(target);
		this.employeeService.update(emp);
		return ResultMsgFactory.successMsg();
	}
}
